#include <RobotFactoryI.h>

RobotFactoryI::RobotFactoryI()
{
}
 
RobotFactoryI::~RobotFactoryI()
{
}

Robots::RobotSeq
RobotFactoryI::create
(const Ice::StringSeq& addresses,
 const Ice::Current& curr)
{
  IceUtil::Mutex::Lock lock(_m);

  vector<Robots::RobotPrx> robots;
  vector<string>::const_iterator it;
  RobotIPtr servant;

  for (it = addresses.begin();
       it != addresses.end();
       ++it)  
    {
      // Register the servant.
      try
	{
	  servant = new RobotI(*it);
	  robots.push_back
	    (Robots::RobotPrx::uncheckedCast
	     (curr.adapter->add(servant, 
				curr.adapter->getCommunicator()->stringToIdentity(*it))));
	  // Add the servant.
	  _robots[*it] = servant;
	  
	  cout << *it << " registered with the robot platform." << endl;
	}
      catch(const Ice::AlreadyRegisteredException&)
	{
	}
    }
  
  // Looking for "zombies".
  RMap::iterator i = _robots.begin();
  while(i != _robots.end())
    if(i->second->isZombie())
      _robots.erase(i++);
    else
      ++i;
  
  return robots;
}

Robots::RobotSeq
RobotFactoryI::list
(const Ice::Current& curr)
{
  IceUtil::Mutex::Lock lock(_m);

  Robots::RobotSeq prxs;
  RMap::iterator it = _robots.begin();

  while (it != _robots.end())
    {
      if (it->second->isZombie())
	{
	  _robots.erase(it++);
	}
      else
	{
	  prxs.push_back(Robots::RobotPrx::uncheckedCast
			 (curr.adapter->createProxy
			  (curr.adapter->getCommunicator()->stringToIdentity(it->first))));
	  ++it;
	}
    }
  
  return prxs;
}
